import { useCallback, useEffect } from 'react';
import { useAgentsStore } from './index';
import type { FileInfo } from './slices/settings';

// 联网搜索相关hook
export const useWebSearch = () => {
  const webSearchEnabled = useAgentsStore((state) => state.webSearchEnabled);
  const webSearchSettings = useAgentsStore((state) => state.webSearchSettings);
  const setWebSearchEnabled = useAgentsStore((state) => state.setWebSearchEnabled);
  const updateWebSearchSettings = useAgentsStore((state) => state.updateWebSearchSettings);
  const toggleWebSearch = useAgentsStore((state) => state.toggleWebSearch);

  return {
    webSearchEnabled,
    webSearchSettings,
    setWebSearchEnabled,
    updateWebSearchSettings,
    toggleWebSearch,
  };
};

// 文件选择相关hook
export const useFileSelection = () => {
  const selectedFiles = useAgentsStore((state) => state.selectedFiles);
  const maxSelectedFiles = useAgentsStore((state) => state.maxSelectedFiles);
  const addSelectedFile = useAgentsStore((state) => state.addSelectedFile);
  const removeSelectedFile = useAgentsStore((state) => state.removeSelectedFile);
  const clearSelectedFiles = useAgentsStore((state) => state.clearSelectedFiles);
  const updateSelectedFile = useAgentsStore((state) => state.updateSelectedFile);
  const setSelectedFiles = useAgentsStore((state) => state.setSelectedFiles);

  // 计算相关状态
  const selectedFileCount = selectedFiles.length;
  const canAddMoreFiles = selectedFileCount < maxSelectedFiles;
  const isMaxFilesReached = selectedFileCount >= maxSelectedFiles;

  // 便捷方法
  const handleFileSelect = useCallback((file: FileInfo) => {
    if (canAddMoreFiles) {
      addSelectedFile(file);
    }
  }, [canAddMoreFiles, addSelectedFile]);

  const handleFileRemove = useCallback((fileId: string) => {
    removeSelectedFile(fileId);
  }, [removeSelectedFile]);

  const isFileSelected = useCallback((fileId: string) => {
    return selectedFiles.some(file => file.id === fileId);
  }, [selectedFiles]);

  const getSelectedFileById = useCallback((fileId: string) => {
    return selectedFiles.find(file => file.id === fileId);
  }, [selectedFiles]);

  return {
    selectedFiles,
    selectedFileCount,
    maxSelectedFiles,
    canAddMoreFiles,
    isMaxFilesReached,
    addSelectedFile,
    removeSelectedFile,
    clearSelectedFiles,
    updateSelectedFile,
    setSelectedFiles,
    handleFileSelect,
    handleFileRemove,
    isFileSelected,
    getSelectedFileById,
  };
};

// Agents设置相关hook
export const useAgentsSettings = () => {
  const settings = useAgentsStore((state) => state.settings);
  const updateSettings = useAgentsStore((state) => state.updateSettings);
  const updateSetting = useAgentsStore((state) => state.updateSetting);
  const resetSettings = useAgentsStore((state) => state.resetSettings);
  const isSettingsLoaded = useAgentsStore((state) => state.isSettingsLoaded);
  const loadSettings = useAgentsStore((state) => state.loadSettings);
  const saveSettings = useAgentsStore((state) => state.saveSettings);
  const exportSettings = useAgentsStore((state) => state.exportSettings);
  const importSettings = useAgentsStore((state) => state.importSettings);

  return {
    settings,
    updateSettings,
    updateSetting,
    resetSettings,
    isSettingsLoaded,
    loadSettings,
    saveSettings,
    exportSettings,
    importSettings,
  };
};

// 综合工具hook - 结合联网搜索和文件选择功能
export const useAgentsTools = () => {
  const webSearch = useWebSearch();
  const fileSelection = useFileSelection();
  
  // 获取当前激活的工具状态
  const hasWebSearchEnabled = webSearch.webSearchEnabled;
  const hasFilesSelected = fileSelection.selectedFileCount > 0;
  const hasAnyToolsActive = hasWebSearchEnabled || hasFilesSelected;

  // 工具状态摘要
  const toolsSummary = {
    webSearch: {
      enabled: hasWebSearchEnabled,
      provider: webSearch.webSearchSettings.provider,
    },
    fileSelection: {
      count: fileSelection.selectedFileCount,
      maxFiles: fileSelection.maxSelectedFiles,
      files: fileSelection.selectedFiles.map(f => ({
        id: f.id,
        name: f.name,
        type: f.type,
      })),
    },
  };

  return {
    webSearch,
    fileSelection,
    hasWebSearchEnabled,
    hasFilesSelected,
    hasAnyToolsActive,
    toolsSummary,
  };
};

// Agents初始化hook
export const useAgentsInitialization = () => {
  const isSettingsLoaded = useAgentsStore((state) => state.isSettingsLoaded);
  const loadSettings = useAgentsStore((state) => state.loadSettings);

  // 自动加载设置
  useEffect(() => {
    if (!isSettingsLoaded) {
      loadSettings();
    }
  }, [isSettingsLoaded, loadSettings]);

  return {
    isSettingsLoaded,
  };
};

// 文件上传处理hook
export const useFileUpload = () => {
  const { handleFileSelect, isFileSelected, canAddMoreFiles } = useFileSelection();

  const handleFileUpload = useCallback(async (files: FileList | File[]) => {
    const fileArray = Array.from(files);
    
    for (const file of fileArray) {
      if (!canAddMoreFiles) break;
      
      const fileInfo: FileInfo = {
        id: `${file.name}-${file.lastModified}-${file.size}`,
        name: file.name,
        path: file.name, // 在web环境中，通常只有文件名
        size: file.size,
        type: file.type || file.name.split('.').pop() || 'unknown',
        lastModified: file.lastModified,
      };

      // 检查是否已经选择过这个文件
      if (!isFileSelected(fileInfo.id)) {
        // 如果需要读取文件内容，可以在这里添加
        try {
          const content = await readFileContent(file);
          fileInfo.content = content;
        } catch (error) {
          console.warn('Failed to read file content:', error);
        }
        
        handleFileSelect(fileInfo);
      }
    }
  }, [handleFileSelect, isFileSelected, canAddMoreFiles]);

  return {
    handleFileUpload,
  };
};

// 辅助函数：读取文件内容
const readFileContent = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      resolve(e.target?.result as string);
    };
    reader.onerror = reject;
    reader.readAsText(file);
  });
}; 